<template>
  <div>
    <h1>步骤表单</h1>
    <div class="item" v-for="item in config" :key="item.property" @click="showModalHandle(item)">
      <div>
        {{item.label}}：{{nowInfo[item.property]}}
      </div>

    </div>
    <ModalEdit :stepConfig="stepConfig" v-model="modalShow" @saveInfo="saveInfo">
    </ModalEdit>
  </div>
</template>
<script setup>
import ModalEdit from '@/components/modal/modalEdit.vue'
import { onMounted, ref } from 'vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'


const nowInfo = ref({})

const modalShow = ref(false)
const stepConfig = ref([])
onMounted(()=>{
  initData()
})
const initData = ()=>{
  axios.get("http://localhost:8000/getInfo").then(res=>{
    nowInfo.value = res.data.data
  })
}

const showModalHandle = (item)=>{
  let arr = []
  //检查出所有值为空的项目
  config.forEach(configItem =>{
    const _value = nowInfo.value[configItem.property]
    console.log("_value",_value)
    //如果值为空并且不是当前项目则加入arr
    if(!_value && configItem.property !== item.property){
      //拷贝
      const copyConfigItem = JSON.parse(JSON.stringify(configItem));
      copyConfigItem.value = nowInfo.value[configItem.property]
      arr.push(configItem)
    }
  })

  arr.sort((pre,now)=>{
    return pre.step - now.step
  })

  const copyItem = JSON.parse(JSON.stringify(item))
  copyItem.value = nowInfo.value[copyItem.property]
  console.log(item)
  stepConfig.value = copyItem
  modalShow.value = true
  //排序后，添加当前项目到arr首位
  arr.unshift(copyItem)
  stepConfig.value = arr
  console.log("stepConfig",stepConfig)
}

//提交
const saveInfo = (info)=>{
  nowInfo.value[info.property] = info.value
  axios.post("http://localhost:8000/saveInfo",info).then(res=>{
    if(res.data.success){
      ElMessage.success('保存成功')
    } else {
      ElMessage.error('保存失败,'+res.data.data);
    }
  })
  modalShow.value = false
  initData()
}

const config = [
  {
    label:'姓名',
    property:'name',
    inputType:'input',
    props:{
      placeholder:'请输入姓名'
    },
    step:0,
  },
  {
    label:'年龄',
    property:'age',
    inputType:'input',
    props:{
      type:'number',
      placeholder:'请输入年龄'
    },
    step:1,
  },
  {
    label:'工作',
    property:'work',
    inputType:'input',
    props:{
      placeholder:'请输入工作'
    },
    step:2,
  },
  {
    label:'出生日期',
    property:'birthday',
    inputType:'date',
    props:{
      type:'date',
      placeholder:'请选择出生日期',
      format:'YYYY-MM-DD',
      valueFormat:'YYYY-MM-DD',
    },
    step:3,
  },
  {
    label:'学历',
    property:'education',
    inputType:'select',
    props:{
      placeholder:'请选择学历'
    },
    options:{
      "小学":"小学1",
      "初中":"初中1",
      "高中":"高中",
      "大专":"大专",
      "本科":"本科",
    },
    step:4,
  },
  {
    label:'自我介绍',
    property:'introduce',
    inputType:'textarea',
    props:{
      placeholder:'请输入自我介绍'
    },
    step:5,
  },
]

</script>

<style scoped>
.item{
  padding: 15px;
  cursor: pointer;
}
</style>
